import VueRouter from "vue-router";
import Home from '@/views/Home'
import Login from '@/views/Login'
import Register from '@/views/Register'
import Search from '@/views/Search'
import Detail from '@/views/Detail'
import AddCartSuccess from '@/views/AddCartSuccess'
//import ShopCart from '@/views/ShopCart'
import Trade from '@/views/Trade'
import Pay from '@/views/Pay'
import Vue from "vue";
import PaySuccess from '@/views/PaySuccess'
import Center from '@/views/Center'
//二级路由：
import MyOrder from '@/views/Center/MyOrder/index.vue'
import GroupbuyingOrder from '@/views/Center/GroupbuyingOrder/index.vue'
//导入仓库
import store from "@/store/index";

Vue.use(VueRouter) // ✅ 关键：注册 VueRouter 插件
export const router = new VueRouter({
    routes: [
        //路由懒加载  ()=>import ('路径')
        {
            path: '/shopcart', component: ()=>import ('@/views/ShopCart'), meta: { show: true }
        },
        //订单中心页面ordercenter
        {
            path: '/ordercenter', component: Center, meta: { show: false },
            //二级路由配置
            children: [
                {
                    // 当 /user/:id/profile 匹配成功，
                    // UserProfile 会被渲染在 User 的 <router-view> 中
                    path: 'myorder',
                    component: MyOrder
                },
                {
                    // 当 /user/:id/posts 匹配成功
                    // UserPosts 会被渲染在 User 的 <router-view> 中
                    path: 'groupbuyingorder',
                    component: GroupbuyingOrder
                }
            ]
        },
        { name: 'addcartsuccess', path: '/addcartsuccess', component: AddCartSuccess, meta: { show: true } },
        { path: '/', redirect: '/home' },
        { path: '/home', component: Home, meta: { show: true } },
        { path: '/login', component: Login, meta: { show: false } },
        { name: 'detail', path: '/detail/:skuId?', component: Detail },
        //结算交易页面Trade
        { name: 'trade', path: '/trade', component: Trade,
            beforeEnter:(to,from,next)=>{
                if (from.path=='/shopcart') {
                    next()
                }else{
                    next(false)
                }
            }

        },
        //支付页面
        { name: 'pay', path: '/pay', component: Pay,
            beforeEnter:(to,from,next)=>{
                if (from.path=='/trade') {
                    next()
                }else{
                    next(false)
                }
            }
         },
        //支付成功页面
        { name: 'paysuccess', path: '/paysuccess', component: PaySuccess,
            //路由独享守卫
            beforeEnter:(to,from,next)=>{
                //必须从支付页面pay才能跳转到支付成功页面'paysuccess',否则就停留到原先页面
                if (from.path=='/pay') {
                    next()
                }else{
                    next(false)
                }
            }
         },
        { path: '/register', component: Register, meta: { show: false } },
        { name: 'search', path: '/search/:keyword?', component: Search, meta: { show: true } },
    ],
    scrollBehavior(to, from, savedPosition) {
        console.log(from, savedPosition);

        if (to.name == 'detail') {
            // 始终滚动到顶部
            return { top: 0 }
        }
    },
})
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}

//路由全局前置守卫:在路由跳转之间进行判断
router.beforeEach(async (to, from, next) => {
    //to:目标路由
    //from:当前路由
    //next('path'):放行去的路由
    console.log(store);
    let token = store.state.userList.loginUser.token
    //存储是否用登录用户名
    let name = store.state.userList.loginUser.username
    console.log('打印路由判断token:' + token);

    if (token) {
        if (to.path == '/login' || to.path == '/register') {
            return next('/')//去首页
        } else {
            //已经登录了，访问的是非登录和注册页面
            //登录了且拥有用户信息放行
            if (name) {
                return next()
            } else {
                //登录了且没有用户信息
                //在路由跳转之前获取用户信息且放行
                /*    try {
                        
                    } catch (error) {
                        
                    } */
                //先退出登录
                await store.commit('userList/clearLoginUser')
                //重新登录
                return next('/login')
            }
        }
    } else {
        const arrPath = ['/trade', '/pay', '/paysuccess', '/ordercenter','/ordercenter/myorder']
        //存储本来想去的路径
        const toPath=to.path
        if (arrPath.includes(to.path)) {
            // 未登录访问受限路径，跳转 login
            //把未登录的时候想去的信息，存储于地址栏中【路由】
            return next('/login?redirect='+toPath)  // ✅ 注意这里加了 return
        }else{
            //去的不是上述这些路由---就可以放行
            return next()
        }
       
    }

})